package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
@Component
@Tag(name = "公共接口")
@Slf4j
@RequestMapping("/admin/common")
public class CommonController {

//    @Value("${sky.file.static-dir}")
    private String uploadDir = "E:\\work\\static\\";

    @Value("${sky.file.access-url}")
    private String accessUrl; // 前端可访问的 URL 前缀

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws Exception{
        File dir = new File(uploadDir);
        if (!dir.exists() || !dir.isDirectory()) {
            boolean created = dir.mkdirs();
            if(created) {
                log.info("创建文件夹成功 ");
            } else {
                log.warn("创建文件夹失败或已经存在");
            }
        }
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return Result.error("文件名无效");
        }

        // 确保文件路径安全，避免路径遍历攻击
        Path targetLocation = Paths.get(uploadDir).resolve(originalFilename).normalize();
        try {
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            log.info("文件上传成功: {}", originalFilename);
        } catch (IOException e) {
            log.error("文件上传失败: {}", originalFilename, e);
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }

        // 你可以根据实际情况调整返回的文件访问链接
        String fileUrl = accessUrl + originalFilename;
        return Result.success(fileUrl);
    }
}
